
// An attribute to hide warnings for unused code.
#![allow(dead_code)]
// 有三种类型的Struct：
// 1. 命名Struct：命名Struct是指通过struct关键字定义的结构体，其名称以大写字母开头，例如：
struct Point1 {
    x: i32,
    y: i32,
}
// 2. 元组Struct：元组Struct是指通过struct关键字定义的结构体，其名称以大写字母开头，例如：
struct Color(i32, i32, i32);    
// 3. 单元Struct：单元Struct是指通过struct关键字定义的结构体，其名称以大写字母开头，但是没有任何字段，
// 主要是用在泛型中，例如：

struct Empty;


//--------- 正式的代码 ---------//

// A named struct
#[derive(Debug)]
struct Person {
    name: String,
    age: u8,
}

// A unit struct
struct Unit;

// A tuple struct
struct Pair(i32, f32);

// A struct with two fields
struct Point {
    x: f32,
    y: f32,
}

// Structs can be reused as fields of another struct
struct Rectangle {
    // A rectangle can be specified by where the top left and bottom right
    // corners are in space.
    top_left: Point,
    bottom_right: Point,
}

/**
 * 计算矩形面积，用到了解构语法
 */
fn rect_area(rect: Rectangle) -> f32 {
    let Point { x: x1, y: y1 } = rect.top_left;
    let Point { x: x2, y: y2 } = rect.bottom_right;

    ((x2 - x1) * (y2 - y1)).abs()
}

fn square(point: Point, length: f32) -> Rectangle {
    let Point { x, y } = point;
    Rectangle {
        top_left: point,
        bottom_right: Point {
            x: x + length,
            y: y + length,
        },
    }
}
fn main() {
    // Create struct with field init shorthand
    let name = String::from("Peter");
    let age = 27;
    let peter = Person { name, age };

    // Print debug struct
    println!("{:?}", peter);

    // Instantiate a `Point`
    let point: Point = Point { x: 5.2, y: 0.4 };
    let another_point: Point = Point { x: 10.3, y: 0.2 };

    // Access the fields of the point
    println!("point coordinates: ({}, {})", point.x, point.y);

    // Make a new point by using struct update syntax to use the fields of our
    // other one
    // 这里X值指定，Y值使用另一个Point的Y值
    let bottom_right = Point { x: 18.9, ..another_point };

    // `bottom_right.y` will be the same as `another_point.y` because we used that field
    // from `another_point`
    println!("second point: ({}, {})", bottom_right.x, bottom_right.y);

    // Destructure the point using a `let` binding
    let Point { x: left_edge, y: top_edge } = point;

    let _rectangle = Rectangle {
        // struct instantiation is an expression too
        top_left: Point { x: left_edge, y: top_edge },
        bottom_right: bottom_right,
    };

    // Instantiate a unit struct
    let _unit = Unit;

    // Instantiate a tuple struct
    let pair = Pair(1, 0.1);

    // Access the fields of a tuple struct
    println!("pair contains {:?} and {:?}", pair.0, pair.1);

    // Destructure a tuple struct
    // 好在不是关键字
    let Pair(integer, decimal) = pair;

    println!("pair contains {:?} and {:?}", integer, decimal);
}
